package com.digital.welcome.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.digital.welcome.entity.MajorClass;
import com.digital.welcome.entity.UserCollege;
import com.digital.welcome.mapper.MajorClassMapper;
import com.digital.welcome.mapper.UserCollegeMapper;
import com.digital.welcome.response.Result;
import com.digital.welcome.service.MajorClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class MajorClassServiceImpl extends ServiceImpl<MajorClassMapper, MajorClass> implements MajorClassService {


    @Autowired
    private MajorClassMapper majorClassMapper;

    @Autowired
    private UserCollegeMapper userCollegeMapper;

    @Override
    public String getMajorList() {
        List<MajorClass> majorClasses = majorClassMapper.selectList(null);
        return JSON.toJSONString(new Result<>().setCode(200).setMessage("查询成功").setData(majorClasses));
    }

    @Override
    public String inserMajor(String majorClass, String majorClassName) {
        QueryWrapper<MajorClass> wrapper = new QueryWrapper<>();
        Integer count = majorClassMapper.selectCount(wrapper) + 1;
        wrapper.eq("major", majorClass);
        wrapper.eq("major_class_name", majorClassName);
        if (majorClassMapper.selectCount(wrapper) > 0) {
            return JSON.toJSONString(new Result<>().setCode(400).setMessage("已存在该班级"));
        }
        MajorClass object = new MajorClass();
        object.setMajor(majorClass);
        object.setMajorClassName(majorClassName);
        object.setMajorId(count.toString());
        majorClassMapper.insert(object);
        return JSON.toJSONString(new Result<>().setCode(200).setMessage("新增成功"));

    }

    @Override
    public String deleteMajor(String majorClass, String majorClassName) {
        MajorClass majorClassObject = majorClassMapper.selectByMajor(majorClass, majorClassName);
        QueryWrapper<UserCollege> wrapper = new QueryWrapper<>();
        wrapper.eq("major_id", majorClassObject.getMajorId());
        Integer count = userCollegeMapper.selectCount(wrapper);
        if (count > 0) {
            return JSON.toJSONString(new Result<>().setCode(400).setMessage("该班级存在学生，不能删除"));
        }
        QueryWrapper<MajorClass> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("major", majorClass);
        wrapper2.eq("major_class_name", majorClassName);
        majorClassMapper.delete(wrapper2);
        return JSON.toJSONString(new Result<>().setCode(200).setMessage("删除成功"));
    }
}
